package com.dyzx.hbb.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;

import javax.validation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ExcelExportUtil {
    public static <M,R> void exportExcel(HttpServletResponse response, List<M> data, Class<R> asClass,String sheetName) throws IOException {


        response.setContentType("application/octet-stream");
        response.setHeader("content-type", "application/octet-stream");
        response.setCharacterEncoding("utf-8");
        String fileName = System.currentTimeMillis() + ".xlsx";

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        List<R> rs = BeanUtil.copyToList(data, asClass);
        EasyExcel.write(response.getOutputStream(),asClass)
                .sheet(sheetName)
                .doWrite(rs);
    }
    public static <M,R> void exportExcel(HttpServletResponse response, List<M> data, Class<R> asClass) throws IOException {


       exportExcel(response,data,asClass,"sheet1");
    }

    public static <M,R> List<M> importExcel(InputStream inputStream,Class<M> asClass,Class<R> asClassImport) {
        List<M> dataList = new ArrayList<>();
        EasyExcel.read(inputStream, asClassImport, new AnalysisEventListener<R>() {
            @SneakyThrows
            @Override
            public void invoke(R data, AnalysisContext context) {

                ValidatorUtil.validate(data);
                M m = BeanUtil.copyProperties(data, asClass);
                dataList.add(m);
            }



            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 所有数据解析完成后的操作
            }
        }).sheet().doRead();
        return dataList;
    }


}